package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.FineTuningDataset;
import com.micro.ai.models.service.FineTuningDatasetService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 微调数据集控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/datasets")
@Tag(name = "微调数据集管理", description = "微调数据集的增删改查、处理")
public class FineTuningDatasetController {

    @Autowired
    private FineTuningDatasetService datasetService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:dataset:create')")
    @Operation(summary = "创建数据集", description = "创建新的微调数据集")
    public ApiResponse<FineTuningDataset> create(@Valid @RequestBody FineTuningDataset dataset) {
        log.info("创建数据集请求: tenantId={}, name={}", dataset.getTenantId(), dataset.getName());
        dataset.setCreatedBy(getCurrentUsername());
        FineTuningDataset result = datasetService.create(dataset);
        return ApiResponse.success("创建成功", result);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:dataset:update')")
    @Operation(summary = "更新数据集", description = "更新数据集信息")
    public ApiResponse<FineTuningDataset> update(
            @Parameter(description = "数据集ID", required = true) @PathVariable String id,
            @Valid @RequestBody FineTuningDataset dataset) {
        log.info("更新数据集请求: datasetId={}", id);
        
        FineTuningDataset result = datasetService.update(id, dataset);
        return ApiResponse.success("更新成功", result);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:dataset:delete')")
    @Operation(summary = "删除数据集", description = "删除数据集")
    public ApiResponse<Void> delete(
            @Parameter(description = "数据集ID", required = true) @PathVariable String id) {
        log.info("删除数据集请求: datasetId={}", id);
        
        datasetService.delete(id);
        return ApiResponse.successVoid("删除成功");
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuning:dataset:view')")
    @Operation(summary = "获取数据集详情", description = "获取数据集详细信息")
    public ApiResponse<FineTuningDataset> getById(
            @Parameter(description = "数据集ID", required = true) @PathVariable String id) {
        log.info("查询数据集详情: datasetId={}", id);
        
        FineTuningDataset dataset = datasetService.getById(id);
        if (dataset == null) {
            return ApiResponse.error("404", "数据集不存在");
        }
        
        return ApiResponse.success(dataset);
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuning:dataset:view')")
    @Operation(summary = "分页查询数据集", description = "根据条件分页查询数据集列表")
    public ApiResponse<Page<FineTuningDataset>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        log.info("分页查询数据集: pageNum={}, pageSize={}", pageNum, pageSize);
        
        Page<FineTuningDataset> page = datasetService.pageQuery(pageNum, pageSize, tenantId, keyword, status);
        return ApiResponse.success(page);
    }

    @PostMapping("/{id}/process")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:dataset:update')")
    @Operation(summary = "处理数据集", description = "开始处理数据集")
    public ApiResponse<Void> process(
            @Parameter(description = "数据集ID", required = true) @PathVariable String id) {
        log.info("处理数据集请求: datasetId={}", id);
        
        datasetService.process(id);
        return ApiResponse.successVoid("处理成功");
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null ? authentication.getName() : "system";
    }
}

